package com.sun.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockTest {
    public static void main(String[] args) {
        Lock lock = new ReentrantLock();
        Ticket ticket = new Ticket();
        new Thread(() -> {
            for (int i = 0; i < 60; i++) {
                try {
                    lock.lock();
                    ticket.sale();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 60; i++) {
                try {
                    lock.lock();
                    ticket.sale();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }, "B").start();

        new Thread(() -> {
            for (int i = 0; i < 60; i++) {
                try {
                    lock.lock();
                    ticket.sale();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }, "C").start();
    }
}


//资源类
class Ticket {
    int num = 50;

    //操作方法
    public void sale() {
        if (num > 0) {
            System.out.println(Thread.currentThread().getName() + "卖出了：" + num-- + "剩下:" + num);
        }
    }
}
